var express = require('express');
var router = express.Router();
// 导入MySQL模块
var mysql = require('mysql');
var dbConfig = require('../DB/dbConf');
var userSQL = require('../DB/usersql');
// 使用DBConfig.js的配置信息创建一个MySQL连接池
var pool = mysql.createPool( dbConfig);
//导入uuid
var uuid=require('node-uuid');
//导入二维码模块
var qr_image = require('qr-image');
//加密包
var crypto = require('crypto');

//返回主页
router.get('/',(req,res,next)=>{
  return res.redirect('home.html');
  next();
});
//获取用户信息
router.get('/getUserInfo',function(req,res,next) {
  pool.getConnection((err,connection)=>{
    connection.query(userSQL.getUserById,req.query.uid,(err,resutls)=>{
        if (err) throw err;
        if(resutls.length>0){
          res.end(JSON.stringify(resutls));
        }else res.end('null');
    });
    connection.release();
  }); 
});
//生成2分钟变化的二维码
//获取当前时间 
var qrcode_time=Date.now();
//保存加密串
var md5str;
router.get('/qrcode',function(req,res){

  if(Date.now()- qrcode_time>1000*120){
    qrcode_time=Date.now();
    console.log('新时间！');
  }
  md5str=crypto.createHash('md5').update(qrcode_time.toString()).digest('hex');
  res.type('png');  
  qr_image.image(md5str).pipe(res);  
});
//返回字符串
router.get('/decode',function(req,res,next){
  console.log(req.session)
  res.json(md5str);
});
//校验二维码并写入数据库
router.post('/received_qrcode',function(req,res,next){
  //未登录返回
  console.log(req.body.up_date);
  var up_date= JSON.parse(req.body.up_date);
  console.log(up_date);
  if (up_date[0].userID==null) {
    res.json({'msg':'未登录！'});
    return
  }
  //允许迟到时间
  // var later = req.query.later*1000*60;
  var later=20*1000*60;
  // //获取上课时间
  // var begintime = new Date().toLocaleDateString()+" "+req.query.classbegin;
  var begintime = new Date().toLocaleDateString()+' '+new Date().toLocaleTimeString();
  var btnumber = new Date(begintime).getTime();
  // //获取上课节次
  // var classnode = req.query.classnode;
  var classnode = 1;
  
  console.log('时间:'+new Date(begintime).getTime()+" 现在时间："+Date.now()+" 延迟时间:"+(btnumber+later));
  console.log("later:"+later+" begintime:"+begintime+" classnode:"+classnode);
  //获取签到用户
  // var userid = req.session.userid;
  var userid=up_date[0].userID;
  //校验二维码begintime
  // var qrcode = req.query.qrcode;
  var qrcode = up_date[0].bitmap;
  //判断是否在上课前
  var state;
  if(btnumber>Date.now() && md5str==qrcode){
    //在上课时间前
    state=1;
  }else if(btnumber<Date.now() && (btnumber+later)>Date.now() && md5str==qrcode){
    // 迟到20分钟内
    state=0;
  }else{
    //无签到
    state=-1;
  }
// 写记录到数据库
  pool.getConnection(function(err,connection){
    if(err) throw err;
    var args=[uuid.v1(),userid,classnode,new Date().toLocaleDateString(),state];
    connection.query("insert into sign_in values(?,?,?,?,?)",args,function(err,results){
      if(err) throw err;
      if(results.affectedRows>0){
        res.json({'result':'1','classnode':args[2],'date':args[3],'state':state});
      }else{
        res.json({'result':'0','classnode':args[2],'date':args[3],'state':state});  
      }
    });
    connection.release();
  });
});

// 获取个人考勤记录
router.get('/listPersonRecord',(req,res,next)=>{
  var userid= req.query.id;
  pool.getConnection((err,connection)=>{
    if(err) throw err;
    var sql='SELECT u.username,s.node,s.time,s.state FROM sign_in AS s LEFT JOIN `user` AS u ON(s.userid=u.uid) WHERE s.userid=?';
    connection.query(sql,userid,(err,results)=>{
      if(err) throw err;
      res.json(results);
    });
    connection.release();
  });
});

// 手动录入数据服务端接口
router.get('/aaa',(req,res,next)=>{
  // 饮料
  var drinks=req.query.drinks;
  // 考勤
  var check=req.query.check;
  // 酒水
  var wine=req.query.wine;
  // 工作
  var work=req.query.work;
  // 游戏
  var game=req.query.game;
  // 健身
  var sport=req.query.sport;
  var args=[uuid.v1(),drinks,check,wine,work,game,sport];
  pool.getConnection((err,connection)=>{
    if(err) throw err;
    connection.query('INSERT INTO inputdata VALUES(?,?,?,?.?,?,?)',args,(err,results)=>{
      if(err) throw err;
      if (results.affectedRows>0) {
        res.json({'msg':'1'});
      }else{
        res.json({'msg':'0'});
      }
    });
    connection.release();
  });
});
// 录入课程评分
router.post('/inputPersonScore',function(req,res,next){
  // 评分数组
  var score=req.body.score;
  // 用户id
  var userid=req.session.userid;
  // 总成绩(字符数组转数字字符对象)
  var allscore=JSON.parse('['+score+']');
  var sum=0;
  allscore.forEach(element => {
    sum+=element;
  });
  pool.getConnection((err,connection)=>{
    if(err) throw err;
    connection.query('INSERT INTO course_score VALUES(?,?,?,?)',[uuid.v1(),userid,score.join(','),sum],(err,results)=>{
      if(err) throw err;
      if(results.affectedRows>0){
        res.json({'msg':1});
      }else{
        res.json({'msg':0});
      }
    });
    connection.release();
  });
});

//查询个人签到历史
router.post('/qr_history',function(req,res){
  
	//通过session获取用户id
	//var uid = req.session.userid;
	 var uid = 3;
  pool.getConnection((err,connection)=>{
    connection.query('select * from sign_in where userid =?',[uid],(err,results)=>{
      if(err) throw err;
      var qrlist = JSON.stringify(results);
      res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
      res.write(qrlist);
      res.end();
    });
    connection.release(); 
  });
});

module.exports = router;

